package org.rsbot.log;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.logging.Level;
import java.util.logging.Logger;

public class LogOutputStream extends OutputStream
{
  private static final String LINE_SEPARATOR = System.getProperty("line.separator");

  protected boolean hasBeenClosed = false;

  protected ByteBuffer buffer = ByteBuffer.allocate(2048);
  public static final int DEFAULT_BUFFER_LENGTH = 2048;
  protected Logger category;
  protected Level priority;

  public LogOutputStream(Logger paramLogger, Level paramLevel)
    throws IllegalArgumentException
  {
    if (paramLogger == null)
      throw new IllegalArgumentException("cat == null");
    if (paramLevel == null) {
      throw new IllegalArgumentException("priority == null");
    }
    this.priority = paramLevel;
    this.category = paramLogger;
  }

  public void close()
  {
    flush();
    this.hasBeenClosed = true;
  }

  public void flush()
  {
    int i = this.buffer.position();
    if (i == 0) {
      return;
    }

    if (i == LINE_SEPARATOR.length())
    {
      if (((char)this.buffer.get(0) == LINE_SEPARATOR.charAt(0)) && ((i == 1) || ((i == 2) && ((char)this.buffer.get(1) == LINE_SEPARATOR.charAt(1)))))
      {
        reset();
        return;
      }
    }

    this.category.log(this.priority, new String(this.buffer.array()));
    reset();
  }

  private void reset() {
    this.buffer.clear();
  }

  public void write(int paramInt)
    throws IOException
  {
    if (this.hasBeenClosed) {
      throw new IOException("The stream has been closed.");
    }

    if (paramInt == 0) {
      return;
    }

    if (this.buffer.position() >= this.buffer.capacity())
    {
      ByteBuffer localByteBuffer = ByteBuffer.allocate(this.buffer.capacity() * 2);
      localByteBuffer.put(this.buffer);
      this.buffer = localByteBuffer;
    }

    this.buffer.put((byte)paramInt);
  }
}